package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.acticle.domain.Destination;
import cn.wolfcode.luowowo.acticle.domain.StrategyDetail;
import cn.wolfcode.luowowo.acticle.domain.Travel;
import cn.wolfcode.luowowo.acticle.domain.TravelContent;
import cn.wolfcode.luowowo.acticle.query.TravelQuery;
import cn.wolfcode.luowowo.acticle.service.*;
import cn.wolfcode.luowowo.acticle.vo.TravelStatisVO;
import cn.wolfcode.luowowo.cache.prefix.TravelStatisKeyPrefix;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Value("${file.path}")
    private String filePath;

    @Reference
    private ITravelService travelService;

    @Reference
    private ITravelContentService travelContentService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IRegionService regionService;

    @Reference
    private ITravelStatisRedisService travelStatisRedisService;

    @RequestMapping("detail")
    public String detail(Model m, Long id) {
        Travel travel = travelService.get(id);
        m.addAttribute("detail", travel);

        Long destId = travel.getDest().getId();
        List<Destination> toasts = destinationService.getToastById(destId);
        if (toasts != null) {
            toasts.remove(toasts.size() - 1);
        }
        //关联攻略
        List<StrategyDetail> sds = strategyDetailService.queryStrategyDetailByDestId(destId);
        m.addAttribute("sds", sds);

        //关联游记
        List<Travel> ts = travelService.queryTravelByDestId(destId);
        m.addAttribute("ts", ts);
        Collections.reverse(toasts);
        m.addAttribute("toasts", toasts);

        //关联评论数据
        TravelCommentQuery ctqo = new TravelCommentQuery();
        ctqo.setTravelId(id);
        ctqo.setPageSize(Integer.MAX_VALUE);
        Page<TravelComment> page = travelCommentService.findByTravelId(ctqo);
        m.addAttribute("list",page.getContent());

        //添加查看次数 +1
        travelStatisRedisService.viewIncrease(TravelStatisKeyPrefix.TRAVEL_STATIS_VO, id);

        //查询redis中该游记的统计信息
        TravelStatisVO vo = travelStatisRedisService.getStatisVo(id);
        m.addAttribute("vo", vo);
        return "travel/detail";
    }

    @RequestMapping("")
    public String list(Model m, @ModelAttribute("qo") TravelQuery qo) {
        m.addAttribute("pageInfo", travelService.query(qo));
        TravelCommentQuery ctqo = new TravelCommentQuery();
        ctqo.setCurrentPage(1);
        ctqo.setPageSize(5);
        Page<TravelComment> tcs = travelCommentService.query(ctqo);
        m.addAttribute("tcs", tcs.get());
        return "travel/list";
    }

    @RequireLogin
    @RequestMapping("input")
    public String input(Model m, Long id) {
        List<Map<String, Object>> destByDeep = regionService.getDestByDeep(3);
        m.addAttribute("regions", destByDeep);
        if (id != null) {
            TravelContent travelContent = travelContentService.get(id);
            Travel travel = travelService.get(id);
            travel.setTravelContent(travelContent);
            m.addAttribute("tv", travel);
        }
        return "travel/input";
    }

    @RequireLogin
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);

        return new AjaxResult().addData(id);
    }

    //添加
    @RequireLogin
    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(Model model, TravelComment comment, int floor, @UserParam UserInfo userInfo) {
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setLevel(userInfo.getLevel());

        TravelComment ref = comment.getRefComment();
        if (ref != null) {
            comment.setRefComment(travelCommentService.get(ref.getId()));
        }

        String cid = travelCommentService.save(comment);
 /*       model.addAttribute("c", travelCommentService.get(cid));
        TravelCommentQuery qo = new TravelCommentQuery();
        model.addAttribute("floor", floor + 1);*/
//        return "travel/commentTpl";
        return new AjaxResult();
    }


    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    //攻略点赞thumbUp
    @RequestMapping("travelThumbup")
    @ResponseBody
    public Object strategyThumbup(Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            return new AjaxResult("请先登录", 102);
        }
        boolean b = travelStatisRedisService.thumbupIncrease(TravelStatisKeyPrefix.TRAVEL_STATIS_THUMBUP, tid, userInfo.getId());
        return new AjaxResult(b, "")
                .addData(travelStatisRedisService.getStatisVo(tid));
    }

    //收藏favor
    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            return new AjaxResult("请先登录", 102);
        }
        boolean ret = travelStatisRedisService.favor(TravelStatisKeyPrefix.TRAVEL_STATIS_FAVOR, tid, userInfo.getId());
        TravelStatisVO vo = travelStatisRedisService.getStatisVo(tid);
        return new AjaxResult(ret, "").addData(vo);
    }

/*    @RequireLogin
    @RequestMapping("commentAdd")
    @ResponseBody
    public Object commentAdd(TravelComment comment,@UserParam UserInfo userInfo){
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setLevel(userInfo.getLevel());
        return new AjaxResult();
    }*/
}
